package first.codeTop.meituan;


import java.util.Arrays;
import java.util.HashMap;

public class Leetcode1 {
    // 两数之和
    public static void main(String[] args) {
        int[] nums = {2, 4, 3, 7};
        int target = 11;
        int[] ints = twoSum(nums, target);
        for (int i : ints) {
            System.out.println(i);
        }
    }

    // 注意数组是无序的
    public static int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i=0; i<nums.length; i++) {
            if (map.containsKey(target-nums[i])) {
                result[0] = map.get(target-nums[i]);
                result[1] = i;
                break;
            }
            map.put(nums[i], i);
        }
        return result;
    }

    // 数组有序时，
    public static int[] twoSum1(int[] nums, int target) {
        int[] result = new int[2];
        Arrays.sort(nums);
        int i = 0;
        int j = nums.length-1;
        while (i < j) {
            if (nums[i] + nums[j] > target) {
                j--;
            } else if (nums[i] + nums[j] < target) {
                i++;
            } else {
                result[0] = i;
                result[1] = j;
                break;
            }
        }
        return result;
    }
}
